package Analyser;

import java.util.HashMap;

import communication.Communicator;

import pacman.Ghost;
import sensors.UltrasonicSensor;

import maze.Direction;
import maze.Location;

public class SectorAnalyserV1 implements SectorAnalyser {

	@Override
	public HashMap<Direction, DistanceToWall> ExploreSector(Ghost ghost) {

		HashMap<Direction, DistanceToWall> ret = new HashMap<Direction, DistanceToWall>();
		UltrasonicSensor ultrasonicSensor = ghost.getUltrasonicSensor();

		Direction[] directions = new Direction[4];
		directions[0] = Direction.NORTH;
		directions[1] = Direction.EAST;
		directions[2] = Direction.SOUTH;
		directions[3] = Direction.WEST;

		//Gebruikt BARCODE commando richtingen
		Direction direction = ghost.generateDirection(ghost.getRotation());
		if (direction == Direction.SOUTH) { //Kijkt nr zuiden
			shiftArray(directions, 2);
		} else if (direction == Direction.WEST) { //Kijkt naar westen
			shiftArray(directions, 1);
		} else if (direction == Direction.EAST) { //Kijkt naar oosten
			shiftArray(directions, 3);
		}
		
		int i = 0;
		int[] walls = new int[4];
		int[] distances = new int[4];
		while (i < 4) {
			/**
			 * Een waarde van 0 duidt aan dat er geen obstakel
			aanwezig is. De waarde 1 duidt op een obstakel . Ten slotte
			duidt de waarde 2 er op dat de noordzijde niet is onderzocht.
			 */
			int distance = ghost.getUltrasonicValue();
			distances[i] = distance;
			
			if (distance < 23) {
				walls[i] = 1;

			}
				
			//nog geen rekening gehouden dat 255 errorwaarde kan zijn
			else {
				walls[i] = 2;
			}
			ghost.rotateSensorMotor(-90);
			i++;
		}
		
		ghost.resetSensorMotor();
		
		for(int k=0; k<directions.length; k++)
		{
			ret.put(directions[k], new DistanceToWall(walls[k], distances[k]));
		}
		
		return ret;
	}


	
	private int interpretPositionSensor(int sensorRotation, int xOffsetSensor, int yOffsetSensor, int distance) {
		int result= distance;
		int sensorRot = (sensorRotation%360+360)%360;
		switch(sensorRot){
		case 0: result+=xOffsetSensor;
		break;
		case 90: result+=yOffsetSensor;
		break;
		case 180: result-=xOffsetSensor;
		break;
		case 270: result-=yOffsetSensor;
		break;
		}
		return result;
	}

	public Direction[] shiftArray(Direction[] directions, int amount){
		for (int j = 0; j < amount; j++) {
			Direction a = directions[directions.length - 1];
            int i;
            for (i = directions.length - 1; i > 0; i--)
            	directions[i] = directions[i - 1];
            directions[i] = a;
		}
		return directions;
	}

}
